package com.doublefish.doublefishrobot.ui.home.service;

import android.app.Activity;
import android.content.Context;

import com.alibaba.fastjson.JSONObject;
import com.doublefish.doublefishrobot.R;
import com.doublefish.doublefishrobot.ui.home.bean.FirmwareInfoBean;
import com.doublefish.doublefishrobot.ui.home.bean.FirmwareInfoResponseBean;
import com.doublefish.doublefishrobot.utils.VersionCompareUtils;
import com.doublefish.doublefishrobot.utils.db.DataBaseApi;
import com.doublefish.doublefishrobot.utils.db.TimeStampUtils;
import com.doublefish.doublefishrobot.utils.encrypt.FileBase64Encoder;
import com.doublefish.doublefishrobot.utils.network.OKHttpApi;

import java.io.File;

/**
 * 作者:dugaofeng on 2024/11/7 17:33
 */
public class FirmwareService {

    //region   获取最新固件版本号

    /*
     *   获取最新固件版本号
     *      model  型号 int  1.超8  2.超6
     * */
    public static void getFirmwareVersion(Context context, int model, FirmwareService.OnFirmwareServiceCallback callback) {
        if (callback == null) {
            return;
        }
        if (model == 0) {
            callback.onFailure(context.getString(R.string.device_type_err));
            return;
        }
        //查询数据库
        DataBaseApi.queryFirmwareInfo(model, new DataBaseApi.OnFirmwareInfoListner() {
            @Override
            public void onCallback(boolean suc, FirmwareInfoBean bean) {
                if (suc) {
                    if (bean == null) {
                        //本地没有数据 去服务器读取
                        requestRemoteFirmwareInfo(context, model, bean, callback);
                    } else {
                        if (TimeStampUtils.isIntraday(bean.getUpdateTime())) {
                            //数据一天内
                            callback.onSuccess(bean);
                        } else {
                            //超出一天 去服务器读取
                            requestRemoteFirmwareInfo(context, model, bean, callback);
                        }
                    }
                } else {
                    //本地查询失败 去服务器读取
                    requestRemoteFirmwareInfo(context, model, bean, callback);
                }
            }
        });
    }

    private static void requestRemoteFirmwareInfo(Context context, int model, FirmwareInfoBean localBean, FirmwareService.OnFirmwareServiceCallback callback) {
        OKHttpApi.getFirmwareVersion(context, model, new OKHttpApi.OkHttpCallback() {
            @Override
            public void onNetworkPermissionError() {
                callback.onNetworkPermissionError();
            }

            @Override
            public void onCallback(boolean success, String response) {
                if (success) {
                    FirmwareInfoResponseBean bean = JSONObject.parseObject(response, FirmwareInfoResponseBean.class);
                    FirmwareInfoBean remoteBean = bean.getData();
                    if (bean.getCode() == 0) {
                        if (remoteBean != null && remoteBean.getModel() == model) {
                            if (localBean == null) {
                                callback.onSuccess(remoteBean);
                                saveFirmwareInfo(remoteBean);
                            } else {
                                //版本号是否递增
                                int res = VersionCompareUtils.compare(localBean.getVer(), remoteBean.getVer());
                                if (res == 1) {
                                    //递增
                                    remoteBean.setTid(localBean.getTid());
                                    callback.onSuccess(remoteBean);
                                    //保存到数据库
                                    saveFirmwareInfo(remoteBean);
                                } else {
                                    //其他
                                    callback.onSuccess(localBean);
                                }
                            }
                        } else {
                            if (localBean == null) {
                                callback.onFailure(context.getString(R.string.no_data));
                            } else {
                                callback.onSuccess(localBean);
                            }
                        }
                    } else {
                        if (localBean == null) {
                            callback.onFailure(bean.getMsg());
                        } else {
                            callback.onSuccess(localBean);
                        }
                    }
                } else  {
                    if (localBean == null) {
                        callback.onFailure(response);
                    } else {
                        callback.onSuccess(localBean);
                    }
                }
            }
        });
    }

    private static void saveFirmwareInfo(FirmwareInfoBean bean) {
        DataBaseApi.saveFirmwareInfo(bean, null);
    }

    public interface OnFirmwareServiceCallback {
        void onNetworkPermissionError();

        void onSuccess(FirmwareInfoBean bean);
        void onFailure(String err);
    }
    //endregion

    //region 下载固件

    //检查本地是否存在固件
    public static void checkBinIsExist(Context context,FirmwareInfoBean bean, OnFirmwareBinExistCallback callback) {
        if (callback == null) {
          return;
        };
//        String dirPath = Environment.getExternalStorageDirectory().toString();
        // FIXME: 2025/1/21 修改本地目录
        //由于部分机型 使用Environment.getExternalStorageDirectory() 时，会dir.mkdirs()失败
        //改为使用 context.getExternalFilesDir(null)
//        String dirPath = Environment.getExternalStorageDirectory().toString();
        String dirPath = context.getExternalFilesDir(null).toString();
        // 获取目录
        String binDir = dirPath + "/doublefish_bin/";
        //1.检查文件夹是否存在
        File dir = new File(binDir);
        if (!dir.exists()) {
            //创建文件夹
            dir.mkdirs();
            callback.onCalback(false, null, null);
            return;
        }
        //2.检查文件是否存在
        String path = binDir + bean.getModel() + "_" + bean.getVer() + ".bin";
        File file = new File(path);
        if (!file.exists()) {
            callback.onCalback(false, null, null);
            return;
        }
        //3.验证文件是否完整
        String code = FileBase64Encoder.hash(file);
        if (code.length() != 0 && code.equals(bean.getHash())) {
            //验证通过
            callback.onCalback(true, path, code);
        } else {
            //验证不通过 删掉文件
            file.delete();
            callback.onCalback(false, null, null);
        }
    }

    //下载升级文件
    public static void downloadFile(Activity activity, String url, String path, String hash, OnFirmwareDownloadCallback callback) {
        OKHttpApi.downloadFile(activity, url, path, new OKHttpApi.OkHttpFileDownloadCallback() {
            @Override
            public void onNetworkPermissionError() {
                if (callback != null) {
                    callback.onNetworkPermissionError();
                }
            }

            @Override
            public void onDownloadProgress(long size) {
                if (callback != null) {
                    callback.onProgress((int) size);
                }
            }
            @Override
            public void onDownloadCallback(boolean success, String path, String msg) {
                if (callback == null) {
                    return;
                }
                if (!success) {
                    //主线程 回调数据
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            callback.onCalback(false, msg);
                        }
                    });
                    return;
                }

                File file = new File(path);
                if (!file.exists()) {
                    callback.onCalback(false, activity.getString(R.string.fail_download_tips));
                    return;
                }
                //验证文件是否完整
                String code = FileBase64Encoder.hash(file);
                //主线程 回调数据
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (code.length() != 0 && code.equals(hash)) {
                            //验证通过
                            callback.onCalback(true, null);
                        } else {
                            //验证不通过 删掉文件
                            file.delete();
                            callback.onCalback(false, activity.getString(R.string.file_verification_error_tips));
                        }
                    }
                });
            }
        });
    }


    public interface OnFirmwareBinExistCallback {
        void onCalback(boolean suc,String path,String hash);
    }
    public interface OnFirmwareDownloadCallback {
        void onNetworkPermissionError();
        void onProgress(int size);
        void onCalback(boolean suc,String msg);
    }

    //endregion

}

